package com.example.dw.controller;

import com.example.dw.common.Result;
import com.example.dw.dto.*;
import com.example.dw.entity.Order;
import com.example.dw.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/")
@Tag(name = "订单管理", description = "订单相关的API接口")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 获取用户所有订单
     */
    @PostMapping("/orderAll")
    @Operation(summary = "获取用户所有订单", description = "根据用户ID获取其所有订单")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取订单列表"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Map<String, Object>> getAllOrders(HttpServletRequest request,
                                                     @RequestBody OrderQueryDTO queryDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Map<String, Object> result = orderService.getAllOrders(userid, queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户所有订单失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户所有订单（Web端）
     */
    @PostMapping("/orderAllWeb")
    @Operation(summary = "获取用户所有订单（Web端）", description = "根据用户ID获取其所有订单（Web端）")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取订单列表"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Map<String, Object>> getOrdersWeb(HttpServletRequest request,
                                                     @RequestBody OrderQueryDTO queryDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Map<String, Object> result = orderService.getOrdersWeb(userid, queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户订单（Web端）失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 创建订单并发起支付
     */
    @PostMapping("/order/pay")
    @Operation(summary = "创建订单并发起支付", description = "根据用户ID创建订单并发起支付")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功创建订单并发起支付"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Map<String, Object>> pay(HttpServletRequest request,
                                           @Validated @RequestBody OrderCreateDTO createDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Map<String, Object> result = orderService.pay(userid, createDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("创建订单并发起支付失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 创建订单并发起支付（Web端）
     */
    @PostMapping("/order/payweb")
    @Operation(summary = "创建订单并发起支付（Web端）", description = "根据用户ID创建订单并发起支付（Web端）")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功创建订单并发起支付"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Map<String, Object>> payWeb(HttpServletRequest request,
                                              @Validated @RequestBody OrderCreateDTO createDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Map<String, Object> result = orderService.payWeb(userid, createDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("创建订单并发起支付（Web端）失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据订单ID获取订单详情
     */
    @GetMapping("/getOrder/{orderid}")
    @Operation(summary = "获取订单详情", description = "根据订单ID获取订单详情")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取订单详情"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "订单不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Order> getOrderById(HttpServletRequest request, @PathVariable Integer orderid) {
        try {
            Integer userid = getCurrentUserId(request);
            Order order = orderService.getOrderById(userid, orderid);
            return Result.success(order);
        } catch (Exception e) {
            log.error("根据订单ID获取订单详情失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 支付回调通知处理
     * 微信支付系统通过这个接口通知我们订单的支付状态
     */
    @PostMapping("/wcnimbiejinlaishouyangluyifaq12/78nongdaoyidibusgun8")
    @Operation(summary = "支付回调通知处理", description = "微信支付系统通过这个接口通知我们订单的支付状态")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功处理支付回调通知"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Map<String, Object>> paymentNotify(@RequestBody PaymentNotifyDTO notifyDTO) {
        try {
            Map<String, Object> result = orderService.paymentNotify(notifyDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("处理支付回调通知失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询微信支付订单状态
     */
    @PostMapping("/getWCOrder/cefgtuysdegfcgywe")
    @Operation(summary = "查询微信支付订单状态", description = "根据订单号查询微信支付订单状态")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功查询订单状态"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "404", description = "订单不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Map<String, Object>> getWCOrder(HttpServletRequest request,
                                                   @RequestBody Map<String, String> params) {
        try {
            Integer userid = getCurrentUserId(request);
            String reqsn = params.get("reqsn");
            Map<String, Object> result = orderService.getWCOrder(reqsn);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询微信支付订单状态失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 继续支付接口
     */
    @PostMapping("/order/continuePay")
    @Operation(summary = "继续支付", description = "根据用户ID继续支付订单")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功继续支付"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Map<String, Object>> continuePay(HttpServletRequest request,
                                                    @Validated @RequestBody OrderPayDTO payDTO) {
        try {
            Integer userid = getCurrentUserId(request);
            Map<String, Object> result = orderService.continuePay(userid, payDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("继续支付失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 从请求中获取当前用户ID
     */
    private Integer getCurrentUserId(HttpServletRequest request) {
        Integer userid = (Integer) request.getAttribute("userid");
        if (userid == null) {
            throw new RuntimeException("未授权访问");
        }
        return userid;
    }
} 